package com.example.memento.download.web;

import com.example.memento.download.model.IpGeoInfo;
import com.example.memento.download.service.IpGeoService;
import com.example.memento.model.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * IP 地址地理位置查询接口
 */
@RestController
@RequestMapping(path = "/ip", produces = MediaType.APPLICATION_JSON_VALUE)
public class IpGeoController {
    
    private final IpGeoService ipGeoService;
    
    public IpGeoController(IpGeoService ipGeoService) {
        this.ipGeoService = ipGeoService;
    }
    
    /**
     * 查询当前请求的 IP 地址地理位置
     */
    @GetMapping("/geo")
    public ApiResponse<IpGeoInfo> getCurrentIpGeo(HttpServletRequest request) {
        String ip = getClientIpAddress(request);
        IpGeoInfo info = ipGeoService.getGeoInfo(ip);
        
        if (info != null) {
            return ApiResponse.<IpGeoInfo>builder()
                    .success(true)
                    .message("查询成功")
                    .data(info)
                    .build();
        } else {
            return ApiResponse.<IpGeoInfo>builder()
                    .success(false)
                    .message("无法获取 IP 地理位置信息（可能是内网 IP 或查询失败）")
                    .data(null)
                    .build();
        }
    }
    
    /**
     * 查询指定 IP 地址的地理位置
     */
    @GetMapping("/geo/{ip}")
    public ApiResponse<IpGeoInfo> getIpGeo(@PathVariable String ip) {
        IpGeoInfo info = ipGeoService.getGeoInfo(ip);
        
        if (info != null) {
            return ApiResponse.<IpGeoInfo>builder()
                    .success(true)
                    .message("查询成功")
                    .data(info)
                    .build();
        } else {
            return ApiResponse.<IpGeoInfo>builder()
                    .success(false)
                    .message("无法获取 IP 地理位置信息（可能是内网 IP 或查询失败）")
                    .data(null)
                    .build();
        }
    }
    
    /**
     * 获取客户端真实 IP 地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        // 处理 X-Forwarded-For 可能包含多个 IP 的情况
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        
        return ip;
    }
}

